/**
 * 生成UUID工具函数
 */

/**
 * 生成标准的UUID v4格式
 * @returns {string} UUID字符串，格式：xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
 */
export function generateUUID(): string {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0
    const v = c === 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}

/**
 * 生成简短的UUID（不带连字符）
 * @returns {string} 32位的UUID字符串
 */
export function generateShortUUID(): string {
  return generateUUID().replace(/-/g, '')
}

/**
 * 生成指定长度的随机ID
 * @param {number} length - ID长度，默认为8
 * @returns {string} 随机ID字符串
 */
export function generateRandomId(length: number = 8): string {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

/**
 * 生成带时间戳的UUID
 * @returns {string} 带时间戳前缀的UUID
 */
export function generateTimestampUUID(): string {
  const timestamp = Date.now().toString(36)
  const uuid = generateRandomId(16)
  return `${timestamp}-${uuid}`
}

/**
 * 验证UUID格式是否正确
 * @param {string} uuid - 要验证的UUID字符串
 * @returns {boolean} 是否为有效的UUID格式
 */
export function isValidUUID(uuid: string): boolean {
  const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
  return uuidRegex.test(uuid)
}

// 默认导出最常用的UUID生成函数
export default generateUUID
